package cn.zcltd.btg.validjsonq.loader;

import cn.zcltd.btg.validjsonq.ValidQLoader;
import cn.zcltd.btg.validq.ValidQ;
import cn.zcltd.btg.validq.validator.IsEmptyValidator;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * loader:验证对象必须为empty
 */
public class IsEmptyLoader implements ValidQLoader {

    @Override
    public void load(ValidQ validQ, JSONObject validationConfig, Object target,
                     String attrField, String attrShortField, String attrFieldName, String attrShortFieldName,
                     Integer level, Integer index) {
        Map<String, String> defaultParams = new HashMap<>();
        defaultParams.put("ctx.field", attrField);
        defaultParams.put("ctx.shortField", attrShortField);
        defaultParams.put("ctx.fieldName", attrFieldName);
        defaultParams.put("ctx.shortFieldName", attrShortFieldName);
        defaultParams.put("ctx.target", String.valueOf(target));

        IsEmptyValidator validator = new IsEmptyValidator();
        validator.setField(attrField);
        validator.setShortField(attrShortField);
        validator.setFieldName(attrFieldName);
        validator.setShortFieldName(attrShortFieldName);

        String msg = validationConfig.getString("msg");
        if (null != msg && msg.trim().length() > 0) {
            msg = "${ctx.fieldName}" + msg;
            validator.setErrorMsg(validQ.getContext().replaceParams(msg, defaultParams));
        }

        index = null == index ? validator.index() : index;
        validQ.on(target, validator, level, index);
    }
}